package com.huawei.aiservice.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huawei.aiservice.entity.pojo.User;
import com.huawei.aiservice.entity.vo.InfoVo;
import com.huawei.aiservice.entity.vo.MultiResponse;
import com.huawei.aiservice.mapper.UserMapper;
import com.huawei.aiservice.service.UserService;
import com.huawei.aiservice.utils.TimeUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Override
    public MultiResponse addUserByChoose(InfoVo infoVo, int type) {
        LambdaQueryWrapper<User> wrapper = Wrappers.<User>lambdaQuery().eq(User::getUserId, infoVo.getId());
        List<User> users = baseMapper.selectList(wrapper);
        if (users.size() > 1) {
            log.warn(String.format("more than one user, user id is %s", infoVo.getId()));
        }
        // 更新
        if (!users.isEmpty()) {
            User userVo = users.get(0);
            infoVoToGiteeUserVo(infoVo, userVo);
            baseMapper.updateById(userVo);
        } else {
            // 新增
            User userVo = new User();
            infoVoToGiteeUserVo(infoVo, userVo);
            baseMapper.insertSelective(userVo);
        }
        return MultiResponse.success(infoVo);
    }

    private void infoVoToGiteeUserVo(InfoVo infoVo, User userVo) {
        userVo.setCreateTime(TimeUtils.getCurrentTime());
        if (StringUtils.isNotBlank(infoVo.getName())) {
            userVo.setCnName(infoVo.getName());
            userVo.setEnName(infoVo.getName());
        }
        if (StringUtils.isNotBlank(infoVo.getLoginName())) {
            String accountHash = infoVo.getLoginName();
            String encrypt = infoVo.getLoginName();
            userVo.setAccount(encrypt);
            userVo.setAccountHash(accountHash);
        }
        if (StringUtils.isNotBlank(infoVo.getEmail())) {
            String emailHash = infoVo.getEmail();
            String encryptEmail = infoVo.getEmail();
            userVo.setEmail(encryptEmail);
            userVo.setEmailHash(emailHash);
        }
        if (StringUtils.isNotBlank(infoVo.getAvatarUrl())) {
            userVo.setImage(infoVo.getAvatarUrl());
        }
        if (StringUtils.isNotBlank(infoVo.getId())) {
            userVo.setUserId(infoVo.getId());
        }
        if (StringUtils.isNotBlank(infoVo.getLoginType())) {
            userVo.setSource(infoVo.getLoginType());
        }
    }
}
